//
//  ReadTheMessageVIew.m
//  YZZX
//
//  Created by Easaa on 15/5/7.
//  Copyright (c) 2015年 Easaa. All rights reserved.
//

#import "ReadTheMessageVIew.h"

#import "HXReadLeaveMsgTableView.h"


@interface ReadTheMessageVIew ()<HXHttpRequestDelegate>
{
    HXReadLeaveMsgTableView    *_readLeaveMsgTableView;
    HXHttpRequest              *_httpRequest;
    UITextField                *_comTextField;
    UIImageView                *_bottomCommentView;
    
    
    NSNumber *numCurLeaveMsgId;
}

@end

@implementation ReadTheMessageVIew



- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor =[UIColor greenColor];
    //self.title = @"聊天界面";
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    
    [self createTableView];
    
    
}


-(void)createTableView
{

    /**
     *  添加底部评论视图
     */
    _bottomCommentView = [[UIImageView alloc] init];
    _bottomCommentView.frame = CGRectMake(0, ScreenHeight - 44 - 44, ScreenWidth, 44);
    _bottomCommentView.backgroundColor = [UIColor clearColor];
    _bottomCommentView.userInteractionEnabled = YES;
    _bottomCommentView.image = [UIImage imageNamed:@"detail_bottom_bg.png"];
    [self.view addSubview:_bottomCommentView];
    
    _comTextField = [[UITextField alloc] init];
    _comTextField.frame = CGRectMake(5.f, (44.f - 35.f)/2.f, 250.f, 35.f);
    _comTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _comTextField.placeholder = @"回复";
    _comTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [_bottomCommentView addSubview:_comTextField];
    [_comTextField addTarget:self action:@selector(textFieldReturnAction) forControlEvents:UIControlEventEditingDidEndOnExit];
    _comTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    
    UIButton *comBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    comBtn.frame = CGRectMake(_comTextField.right + 5.f, _comTextField.top + 2.5f, _bottomCommentView.width - _comTextField.width - 15.f, 30.f);
    [comBtn setTitle:@"发送" forState:UIControlStateNormal];
    [comBtn setBackgroundImage:[UIImage imageNamed:@"top_tongyon_btn01.png"] forState:UIControlStateNormal];
                                //resizeImageFromInsets:UIEdgeInsetsMake(10, 10, 10, 10)]
    
    [comBtn setBackgroundImage:[UIImage imageNamed:@"top_tongyon_btn01_h.png"] forState:UIControlStateHighlighted];
                               // resizeImageFromInsets:UIEdgeInsetsMake(10, 10, 10, 10)]
    [comBtn addTarget:self action:@selector(sendReplyAction:) forControlEvents:UIControlEventTouchUpInside];
    comBtn.showsTouchWhenHighlighted = YES;
    comBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.f];
    [_bottomCommentView addSubview:comBtn];

    
    
    
    

    
    
    
    /**
     *  添加留言及内容回复视图
     */
    _readLeaveMsgTableView = [[HXReadLeaveMsgTableView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, Dev_ScreenHeight - 44 - 60)];
                              
                            
    
                              
    _readLeaveMsgTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _readLeaveMsgTableView.backgroundColor = [UIColor clearColor];
    //[_readLeaveMsgTableView addOneContent:1 andContent:@"中国国民党!中国国民党!中国国民党!中国国民党!中国国民党!中国国民党!中国国民党!"];
    //[_readLeaveMsgTableView addOneContent:2 andContent:@"中国共产党!中国共产党!中国共产党!中国共产党!中国共产党!中国共产党!中国共产党!"];
    [self.view addSubview:_readLeaveMsgTableView];
    [self.view sendSubviewToBack:_readLeaveMsgTableView];

    //_readLeaveMsgTableView.backgroundColor =[UIColor redColor];
    [self creatTopicMessageReadRequest];
    

}

- (void)sendReplyAction:(UIButton *)sender
{
    [self.view endEditing:YES];
    if (StringIsEmpty(_comTextField.text))
    {

        UIAlertView  *AlertView = [[UIAlertView alloc]initWithTitle:nil
                                                            message:@"请输入内容!"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定",nil];
        [AlertView show];
       // [HXTool showTipMessage:@"请输入内容!" InView:self.view];
        return;
    }
    [self creatTopicMessageReplyRequest];
}

- (void)textFieldReturnAction
{
    if ([_comTextField isFirstResponder])
    {
        [_comTextField resignFirstResponder];
    }
}

- (void)creatTopicMessageReadRequest
{
//    [HXTool toastNotification:@"正在加载..."
//                      andView:self.view
//                   andLoading:YES
//                  andIsBottom:NO
//                andIsAutoHide:NO];
    
    NSDictionary *dicParams = @{@"user_id": [XSZ_UICommon useridChangUaerdfLoginBoolString],
                                @"site_id": @"1",
                                @"id": [NSNumber numberWithInteger:[self.id_massge integerValue]]};
    if (_httpRequest == nil)
    {
        _httpRequest = [[HXHttpRequest alloc] init];
        _httpRequest.delegate = self;
    }
    [_httpRequest requestForParams:dicParams andMethod:YZ_TOPICMESSAGES_READ andTag:1002];
}


- (void)creatTopicMessageReplyRequest
{
//    [HXTool toastNotification:@"回复中..."
//                      andView:self.view
//                   andLoading:YES
//                  andIsBottom:NO
//                andIsAutoHide:NO];

    
    NSDictionary *dicParams = @{@"user_id":[XSZ_UICommon useridChangUaerdfLoginBoolString],
                                @"site_id":@"1",
                                @"post_data": @{@"id": numCurLeaveMsgId,
                                                @"Content": _comTextField.text}};
    _comTextField.text = @"";
    if (_httpRequest == nil)
    {
        _httpRequest = [[HXHttpRequest alloc] init];
        _httpRequest.delegate = self;
    }
    [_httpRequest requestForParams:dicParams andMethod:YZ_TOPICMESSAGES_REPLY andTag:1003];
}





#pragma mark - HXHttpRequestDelegate

- (void)requestFinished:(NSString *)responseString andStatusCode:(int)statusCode andTag:(NSInteger)tag
{
    //[HXTool hideToastNofification:self.view];
    if (statusCode == 200)
    {
        if (tag == 1002)
        {
            NSDictionary *dic = [JsonUtil jsonToDic:responseString];
            [self topicMessagesReadResult:dic];
        } else if (tag == 1003)
        {
            NSDictionary *dic = [JsonUtil jsonToDic:responseString];
          [self topicMessageReplyResult:dic];
        }
    }
}

- (void)requestFailed:(NSError *)error andTag:(NSInteger)tag
{
    //[HXTool hideToastNofification:self.view];
}






- (void)topicMessagesReadResult:(NSDictionary *)dic
{
    if ([[dic objectForKey:@"is_success"] boolValue])
    {
        NSString *strData = [dic objectForKey:@"data"];
        NSDictionary *dicData = [JsonUtil jsonToDic:strData];
        if (!DictionaryIsEmpty(dicData))
        {
            NSMutableArray *aryContents = [NSMutableArray array];
            numCurLeaveMsgId = [dicData objectForKey:@"id"];
          
            NSString *strSenderTime = [dicData objectForKey:@"CreationDate"];
            
            
            
            //时间转换
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *date = [dateformatter dateFromString:strSenderTime];
            [dateformatter setDateFormat:@"yyyy-MM-dd"];
           strSenderTime = [dateformatter stringFromDate:date];
            
//            //strSenderTime = [strSenderTime dateStringWithFormatter:@"yyyy-MM-dd HH:mm:ss" convertToFormatter:@"yyyy-MM-dd"];
//           [aryContents addObject:@{textTypeKey: @1,
//                                     textContentKey: [dicData objectForKey:@"Content"],
//                                     textSenderNameKey: [dicData objectForKey:@"SenderName"],
//                                     textSenderTimeKey: strSenderTime}];
            
            if ([[dicData objectForKey:@"SenderId"] unsignedLongValue] == 1)//[HXLoginInstance shareLoginInstance].user_id)
            {//当前用户所发
                [aryContents addObject:@{textTypeKey: @2,
                                         textContentKey: [dicData objectForKey:@"Content"],
                                         textSenderNameKey: [dicData objectForKey:@"SenderName"],
                                         textSenderTimeKey: strSenderTime}];
            } else
            {
                [aryContents addObject:@{textTypeKey: @1,
                                         textContentKey: [dicData objectForKey:@"Content"],
                                         textSenderNameKey: [dicData objectForKey:@"SenderName"],
                                         textSenderTimeKey: strSenderTime}];
            }

           
            NSArray *aryReplices = [dicData objectForKey:@"Replices"];
            if (!ArrayIsEmpty(aryReplices))
            {
                for (NSDictionary *dic in aryReplices)
                {
                    strSenderTime = [dic objectForKey:@"CreationDate"];
                    //时间转换
                    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
                    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSDate *date = [dateformatter dateFromString:strSenderTime];
                    [dateformatter setDateFormat:@"yyyy-MM-dd"];
                    strSenderTime = [dateformatter stringFromDate:date];
                    
                    
//                    strSenderTime = [strSenderTime dateStringWithFormatter:@"yyyy-MM-dd HH:mm:ss" convertToFormatter:@"yyyy-MM-dd"];
                    
                    if ([[dic objectForKey:@"SenderId"] unsignedLongValue] == 1)//[HXLoginInstance shareLoginInstance].user_id)
                    {//当前用户所发
                        [aryContents addObject:@{textTypeKey: @2,
                                                 textContentKey: [dic objectForKey:@"Content"],
                                                 textSenderNameKey: [dic objectForKey:@"SenderName"],
                                                 textSenderTimeKey: strSenderTime}];
                    } else
                    {
                        [aryContents addObject:@{textTypeKey: @1,
                                                 textContentKey: [dic objectForKey:@"Content"],
                                                 textSenderNameKey: [dic objectForKey:@"SenderName"],
                                                 textSenderTimeKey: strSenderTime}];
                    }
                    
                }
            }
            
            [_readLeaveMsgTableView addLeaveMsg:aryContents];
            
        } else
        {
            //[HXTool showTipMessage:@"暂无留言!" InView:self.view];
        }
    } else
    {//失败
        
    }
}


- (void)topicMessageReplyResult:(NSDictionary *)dic
{
    if ([[dic objectForKey:@"is_success"] boolValue])
    {
        NSString *strData = [dic objectForKey:@"data"];
        NSDictionary *dicData = [JsonUtil jsonToDic:strData];
        if (!DictionaryIsEmpty(dicData))
        {
            NSString *strContent = [dicData objectForKey:@"Content"];
            NSString *strSenderName = [dicData objectForKey:@"SenderName"];
            NSString *strSenderTime = [dicData objectForKey:@"CreationDate"];
            
            
            //时间转换
            NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *date = [dateformatter dateFromString:strSenderTime];
            [dateformatter setDateFormat:@"yyyy-MM-dd"];
            strSenderTime = [dateformatter stringFromDate:date];
            
           // strSenderTime = [strSenderTime dateStringWithFormatter:@"yyyy-MM-dd HH:mm:ss" convertToFormatter:@"yyyy-MM-dd"];
            
            [_readLeaveMsgTableView addOneContent:2 Content:strContent senderName:strSenderName senderTime:strSenderTime];
            dispatch_main_async_safe(^{
                [_readLeaveMsgTableView reloadDataFromBottom];
            });
        } else
        {
           // [HXTool showTipMessage:@"暂无内容!" InView:self.view];
        }
    } else
    {//失败
//        NSString *strMsg = [dic objectForKey:@"message"];
       // [HXTool showTipMessage:strMsg InView:self.view];
    }
}




#pragma mark - keyboard notification

- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *keyboardUserInfo = notification.userInfo;
    NSValue *keyboardFrameValue = [keyboardUserInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [keyboardFrameValue CGRectValue];
    NSNumber *numKeyboardDuration = [keyboardUserInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *numCurve = [keyboardUserInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[numKeyboardDuration doubleValue]];
    [UIView setAnimationCurve:[numCurve unsignedIntValue]];
    _bottomCommentView.top = ScreenHeight - keyboardFrame.size.height - 44 - _bottomCommentView.height;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    NSDictionary *keyboardUserInfo = notification.userInfo;
    NSNumber *numKeyboardDuration = [keyboardUserInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *numCurve = [keyboardUserInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[numKeyboardDuration doubleValue]];
    [UIView setAnimationCurve:[numCurve unsignedIntValue]];
    _bottomCommentView.top = ScreenHeight - 44 - _bottomCommentView.height;
    [UIView commitAnimations];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}



@end
